<template>
    <div>
        <div class="top">
            <el-form ref="queryFormRef" style="max-width: 600px; display: flex;" :model="queryParams" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <el-form-item label="关键字" prop="keywords" style="max-width: 300px">
                    <el-input v-model="queryParams.keywords" autocomplete="off" placeholder="菜单名称"
                        @keyup.enter="submitForm" />
                </el-form-item>
                <el-form-item style="margin-left: 20px;">
                    <el-button type="primary" @click="submitForm">
                        <i-ep-search />搜索
                    </el-button>
                    <el-button @click="resetForm">
                        <i-ep-refresh />重置
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="cen">
            <el-button class="addBtns" type="success" @click="adds">
                <template #icon><i-ep-plus /></template>
                新增</el-button>
            <el-table v-loading="loading" :data="menuTableData" style="width: 100%" row-key="id">
                <el-table-column label="菜单名称" width="200">
                    <template #default="scope">
                        <template v-if="scope.row.icon && scope.row.icon.startsWith('el-icon')">
                            <el-icon style="vertical-align: -0.15em">
                                <component :is="scope.row.icon.replace('el-icon-', '')" />
                            </el-icon>
                        </template>
                        <template v-else-if="scope.row.icon">
                            <svg-icon :icon-class="scope.row.icon" />
                        </template>
                        <template v-else>
                            <svg-icon icon-class="menu" />
                        </template>
                        {{ scope.row.name }}
                    </template>
                </el-table-column>
                <el-table-column label="类型" width="180" align="center">
                    <template #default="scope">
                        <el-tag v-if="scope.row.type === MenuTypeEnum.CATALOG" type="warning">
                            目录
                        </el-tag>
                        <el-tag v-if="scope.row.type === MenuTypeEnum.MENU" type="success">
                            菜单
                        </el-tag>
                        <el-tag v-if="scope.row.type === MenuTypeEnum.BUTTON" type="danger">
                            按钮
                        </el-tag>
                        <el-tag v-if="scope.row.type === MenuTypeEnum.EXTLINK" type="info">
                            外链
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="path" label="路由路径" width="200" align="left" />
                <el-table-column prop="component" label="组件路径" width="200" align="left" />
                <el-table-column prop="perm" label="权限标识" width="200" align="center" />
                <el-table-column prop="zip" label="状态" width="120" align="center">
                    <template #default="scope">
                        <el-tag v-if="scope.row.visible === 1" type="success">显示</el-tag>
                        <el-tag v-else type="info">隐藏</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="sort" label="排序" width="100" align="center" />
                <el-table-column fixed="right" label="操作" width="180" align="center">
                    <template #default="scope">
                        <el-button v-if="scope.row.type == 'CATALOG' || scope.row.type == 'MENU'" link type="primary"
                            size="small" @click="adds(scope.row)"><i-ep-plus />新增</el-button>
                        <el-button link type="primary" size="small" @click="handleClick(scope.row)">
                            <i-ep-edit />编辑
                        </el-button>
                        <el-button link type="danger" size="small"
                            @click="dels(scope.$index, scope.row)"><i-ep-delete />删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 弹框 -->
            <el-dialog v-model="dialogTableVisible" :title="title" width="800">
                <el-form ref="ruleFormRefs" style="max-width: 600px" :model="formData" :rules="ruless"
                    label-width="auto" class="demo-ruleForms" :size="formSize" status-icon>
                    <el-form-item label="父级菜单" prop="title">
                        <el-tree-select v-model="formData.parentId" :data="menuOptions" placeholder="选择上级菜单" filterable
                            check-strictly :render-after-expand="false" />
                    </el-form-item>
                    <el-form-item label="菜单名称" prop="name">
                        <el-input v-model="formData.name" />
                    </el-form-item>
                    <el-form-item label="菜单类型" prop="type">
                        <el-radio-group v-model="formData.type">
                            <el-radio value="CATALOG">目录</el-radio>
                            <el-radio value="MENU">菜单</el-radio>
                            <el-radio value="BUTTON">按钮</el-radio>
                            <el-radio value="EXTLINK">外链</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-if="
                        formData.type == MenuTypeEnum.CATALOG ||
                        formData.type == MenuTypeEnum.MENU
                    " label="" prop="path">
                        <template #label>
                            <div>
                                路由路径
                                <el-tooltip placement="bottom" effect="light">
                                    <template #content>
                                        定义应用中不同页面对应的 URL 路径，目录需以 /
                                        开头，菜单项不用。例如：系统管理目录
                                        /system，系统管理下的用户管理菜单 user。
                                    </template>
                                    <i-ep-QuestionFilled class="inline-block" />
                                </el-tooltip>
                            </div>
                        </template>
                        <el-input v-if="formData.type == MenuTypeEnum.CATALOG" v-model="formData.path"
                            placeholder="system" />
                        <el-input v-else v-model="formData.path" placeholder="user" />
                    </el-form-item>
                    <el-form-item v-if="formData.type == MenuTypeEnum.MENU && title == '新增菜单'" prop="component">
                        <template #label>
                            <div>
                                组件路径
                                <el-tooltip placement="bottom" effect="light">
                                    <template #content>
                                        组件页面完整路径，相对于 src/views/，如
                                        system/user/index，缺省后缀 .vue
                                    </template>
                                    <i-ep-QuestionFilled class="inline-block" />
                                </el-tooltip>
                            </div>
                        </template>
                        <el-input v-model="formData.component" placeholder="system/user/index" style="width: 95%">
                            <template v-if="formData.type == MenuTypeEnum.MENU" #prepend>src/views/</template>
                            <template v-if="formData.type == MenuTypeEnum.MENU" #append>.vue</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item v-if="formData.type == MenuTypeEnum.MENU && title == '新增菜单'">
                        <template #label>
                            <div>
                                路由参数
                                <el-tooltip placement="bottom" effect="light">
                                    <template #content>
                                        组件页面使用`useRoute().query.参数名` 获取路由参数值。
                                    </template>
                                    <i-ep-QuestionFilled class="inline-block" />
                                </el-tooltip>
                            </div>
                        </template>
                        <div v-if="!formData.params || formData.params.length === 0">
                            <el-button type="success" plain @click="formData.params = [{ key: '', value: '' }]">
                                添加路由参数
                            </el-button>
                        </div>
                        <div v-else>
                            <div v-for="(item, index) in formData.params" :key="index">
                                <el-input v-model="item.key" placeholder="参数名" class="w-[100px]" />
                                <span class="mx-1">=</span>
                                <el-input v-model="item.value" placeholder="参数值" class="w-[100px]" />
                                <el-icon class="ml-2 cursor-pointer color-[var(--el-color-success)]"
                                    style="vertical-align: -0.15em" v-if="
                                        formData.params.indexOf(item) === formData.params.length - 1
                                    " @click="formData.params.push({ key: '', value: '' })">
                                    <CirclePlusFilled />
                                </el-icon>
                                <el-icon class="ml-2 cursor-pointer color-[var(--el-color-danger)]"
                                    style="vertical-align: -0.15em"
                                    @click="formData.params.splice(formData.params.indexOf(item), 1)">
                                    <DeleteFilled />
                                </el-icon>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item v-if="formData.type !== MenuTypeEnum.BUTTON" label="显示状态" prop="visible">
                        <el-radio-group v-model="formData.visible">
                            <el-radio :value="1">显示</el-radio>
                            <el-radio :value="0">隐藏</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-if="formData.type === MenuTypeEnum.CATALOG || formData.type === MenuTypeEnum.MENU">
                        <template #label>
                            <div>
                                始终显示
                                <el-tooltip placement="bottom" effect="light">
                                    <template #content>
                                        选择“是”，即使目录或菜单下只有一个子节点，也会显示父节点。<br />
                                        选择“否”，如果目录或菜单下只有一个子节点，则只显示该子节点，隐藏父节点。<br />
                                        如果是叶子节点，请选择“否”。
                                    </template>
                                    <i-ep-QuestionFilled class="inline-block" />
                                </el-tooltip>
                            </div>
                        </template>
                        <el-radio-group v-model="formData.alwaysShow">
                            <el-radio :value="1">是</el-radio>
                            <el-radio :value="0">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-if="formData.type === MenuTypeEnum.MENU" label="页面缓存">
                        <el-radio-group v-model="formData.keepAlive">
                            <el-radio :value="1">开启</el-radio>
                            <el-radio :value="0">关闭</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="排序" prop="sort">
                        <el-input-number v-model="formData.sort" style="width:100px" controls-position="right"
                            :min="0" />
                    </el-form-item>
                    <el-form-item v-if="formData.type == MenuTypeEnum.BUTTON" label="权限标识" prop="perm">
                        <el-input v-model="formData.perm" placeholder="sys:user:add" />
                    </el-form-item>
                    <el-form-item v-if="formData.type !== MenuTypeEnum.BUTTON" label="图标" prop="icon">
                        <!-- 图形选择器 -->
                        <IconSelect v-model="formData.icon" />
                    </el-form-item>
                    <el-form-item v-if="formData.type == MenuTypeEnum.CATALOG" label="跳转路由">
                        <el-input v-model="formData.redirect" placeholder="跳转路由" />
                    </el-form-item>
                    <el-form-item class="queryBtn">
                        <div class="dialog-footer">
                            <el-button type="primary" @click="submitForms(ruleFormRefs)">
                                确定
                            </el-button>
                            <el-button @click="resetForms(ruleFormRefs)">取消</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-dialog>

            <!-- 删除弹框 -->
            <el-dialog v-model="dialogVisible" title="警告" width="500" :before-close="handleClose">
                <span>确定要删除该项数据吗?</span>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="delBtns">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
// 调用接口
import { getRoutes, getOptions, getList, add, deleteById, update } from '@/api/menu/index';
// 调用类型
import type { MenuForm, MenuQuery } from '@/api/menu/model'
import SvgIcon from '@/components/SvgIcon/index.vue'
import { MenuTypeEnum } from '@/enums/MenuTypeEnum';
import { DeleteFilled } from '@element-plus/icons-vue';
import IconSelect from '@/components/IconSelect/index.vue';

// 获取接口数据
// 菜单表格数据
const menuTableData = ref<MenuVO[]>([]);
const getRoutesFen = async () => {
    const res = await getList()
    menuTableData.value = res
}

// 获取下拉菜单数据
const menuOptions = ref([])
const getOptionsFen = async () => {
    await getOptions().then((data) => {
        menuOptions.value = [{ value: 0, label: "顶级菜单", children: data }];
    })
}

// 搜索
const loading = ref(false)
const queryFormRef = ref(ElForm);

// 查询参数
const queryParams = reactive<MenuQuery>({});
const validatePass = (rule: any, value: any, callback: any) => {
    loading.value = true
    if (value === '') {
        callback(new Error('请输入搜索值'))
    } else {
        callback()
    }
}

const ruleForm = reactive({
    keywords: ''
})
// 校验
const rules = reactive<FormRules<typeof ruleForm>>({
    keywords: [{ validator: validatePass, trigger: 'blur' }]
})
// 搜索
const submitForm = async () => {
    loading.value = true
    await getList(queryParams).then((data) => {
        menuTableData.value = data
    }).finally(()=>{
        loading.value = false;
    })
}
// 重置
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
// --------------------------------------------------------


// 弹框
const dialogTableVisible = ref(false)
const title = ref('')
const formSize = ref<ComponentSize>('default')
const ruleFormRefs = ref<FormInstance>()

// 初始菜单表单数据
const initialMenuFormData = ref<MenuForm>({
    id: undefined,
    parentId: 0,
    visible: 1,
    sort: 1,
    type: MenuTypeEnum.MENU, // 默认菜单
    alwaysShow: 0,
    keepAlive: 1,
    params: [],
});

// 菜单表单数据
const formData = ref({ ...initialMenuFormData.value });

const ruless = reactive({
    parentId: [{ required: true, message: "请选择顶级菜单", trigger: "blur" }],
    name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
    type: [{ required: true, message: "请选择菜单类型", trigger: "blur" }],
    path: [{ required: true, message: "请输入路由路径", trigger: "blur" }],
    component: [{ required: true, message: "请输入组件路径", trigger: "blur" }],
    visible: [{ required: true, message: "请输入显示状态", trigger: "blur" }],
})

// 确定
// 修改ID
const submitForms = async (formEl: FormInstance | undefined) => {
    // 如果是添加
    if (title.value == '新增菜单') {
        await add(formData.value).then(() => {
            ElMessage({
                message: '添加成功',
                type: 'success',
            })
        }).catch(() => {
            ElMessage({
                message: '添加失败',
                type: 'error',
            })
        })
        getRoutesFen()
        getOptionsFen()
    } else if (title.value == '编辑菜单') {
        const ids = formData.value.id
        await update(ids, formData.value).then(() => {
            ElMessage({
                message: '编辑成功',
                type: 'success',
            })
        }).catch(() => {
            ElMessage({
                message: '编辑失败',
                type: 'error',
            })
        })
        getRoutesFen()
        getOptionsFen()
    }
    dialogTableVisible.value = false
}
// 取消
const resetForms = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    dialogTableVisible.value = false
}


// 添加
const adds = (row) => {
    console.log(row, '123');

    dialogTableVisible.value = true
    title.value = '新增菜单'
    formData.value.parentId = row.id
    formData.value.visible = 1
    formData.value.sort = 1
    formData.value.type = MenuTypeEnum.MENU
    formData.value.alwaysShow = 0
    formData.value.keepAlive = 1
    formData.value.params = []
    formData.value.name = ''
    formData.value.path = ''
    formData.value.component = ''
    formData.value.redirect = ''
    formData.value.icon = ''
}

// 编辑
const handleClick = (row) => {
    dialogTableVisible.value = true
    title.value = '编辑菜单'
    formData.value.id = row.id
    formData.value.parentId = row.parentId
    formData.value.visible = row.visible
    formData.value.sort = row.sort
    formData.value.type = row.type
    formData.value.alwaysShow = row.alwaysShow  //始终显示
    formData.value.keepAlive = row.keepAlive
    formData.value.params = row.params
    formData.value.name = row.name
    formData.value.path = row.path
    formData.value.component = row.component
    formData.value.redirect = row.redirect
    formData.value.icon = row.icon
}

// 删除
const dialogVisible = ref(false)
const delId = ref(0)
const dels = (index, row) => {
    dialogVisible.value = true
    delId.value = row.id
}
// 关闭对话框
const handleClose = (done: () => void) => {
    ElMessageBox.confirm('确定要关闭此对话框吗?')
        .then(() => {
            done()
        })
        .catch(() => {
            // catch error
        })
}
// 删除确认
const delBtns = async () => {
    await deleteById(delId.value)
    getRoutesFen()
    getOptionsFen()
    ElMessage({
        message: '删除成功',
        type: 'success',
    })
    dialogVisible.value = false
}



onMounted(() => {
    getRoutesFen()
    getOptionsFen()
})
</script>

<style scoped>
.top {
    background-color: white;
    height: 60px;
    padding: 15px;
    box-sizing: border-box;
}

.cen {
    margin-top: 20px;
    padding: 20px;
    box-sizing: border-box;
    background-color: white
}

.demo-ruleForms {
    margin-left: 70px;
}

.addBtns {
    margin: 0 0 20px 0;
}
</style>